<template>
  <!-- 标品 -->
  <view class="content" :style="{ paddingTop: statusBarHeight + 'px' }">
    <uni-nav-bar :title="type == '0' ? '修改商品' : '新增商品'" fixed :border="false" height="88rpx" background-color="#fff"
      left-icon="left" @clickLeft="onClickLeft"></uni-nav-bar>

    <view class="main">
      <uni-forms ref="customForm" :rules="customRules" :modelValue="customFormData" :label-width="100">
        <view class="row">
          <view class="col">
            <uni-forms-item label="商品分类:" required name="categoryName">
              <uni-easyinput v-model="customFormData.categoryName" disabled placeholder="" style="width: 100%;"
                adjust-position />
            </uni-forms-item>
          </view>
        </view>
        <view class="row">
          <view class="col">
            <uni-forms-item label="商品名称:" required name="name">
              <uni-easyinput v-model="customFormData.name" placeholder="请输入商品名称，最多15位" style="width: 100%;"
                adjust-position />
            </uni-forms-item>
          </view>
        </view>
        <view class="row">
          <view class="col">
            <uni-forms-item label="商品助记符:" required name="mnemonic">
              <uni-easyinput v-model="customFormData.mnemonic" placeholder="" disabled style="width: 100%;"
                adjust-position />
            </uni-forms-item>
          </view>
        </view>
        <view class="row">
          <view class="col">
            <uni-forms-item label="商品一维码:" name="firstCode">
              <uni-easyinput type="number" v-model="customFormData.firstCode" placeholder="请输入商品一维码" style="width: 100%;"
                adjust-position />
            </uni-forms-item>
          </view>
        </view>
        <view class="row">
          <view class="col2">
            <uni-forms-item label="售价:" required name="storePrice">
              <uni-easyinput type="number" v-model="customFormData.storePrice" placeholder="请输入售价" style="width: 100%;"
                adjust-position />
            </uni-forms-item>
          </view>
          <text>元</text>
        </view>
        <view class="row">
          <view class="col2">
            <uni-forms-item type="number" label="进价:" required name="purchasePrice">
              <uni-easyinput v-model="customFormData.purchasePrice" placeholder="请输入进价" style="width: 100%;"
                adjust-position />
            </uni-forms-item>
          </view>
          <text>元</text>
        </view>
        <view class="row">
          <view class="col2">毛利率：{{ customFormData.grossRate }}%</view>
        </view>
        <view class="row">
          <view class="col2">销售单位：KG</view>
        </view>
      </uni-forms>
      <view class="btnBox" @click="submitForm">
        <text class="btn type-1">确认</text>
      </view>
    </view>
  </view>
</template>

<script>
import { DecimalUtils } from "@/utils/math";
import { pinyin } from "pinyin-pro";
import { reqAddNonstandardCommodity, reqUpdateNonstandardCommodity } from '@/apis/member'
export default {
  name: "AutotrophyGoods",
  data() {
    return {
      type: '0',
      id: '',
      obj: {},
      customFormData: {
        name: '',
        categoryName: '',
        categoryId: '',
        mnemonic: '',
        firstCode: '',
        storePrice: '',
        purchasePrice: '',
        grossRate: '',
        ilk: '1',
        unit: 'KG'
      },
      customRules: {
        name: {
          rules: [
            {
              required: true,
              errorMessage: '请输入商品名称',
            },
            {
              minLength: 1,
              maxLength: 15,
              errorMessage: '商品名称最长为15个字符',
            },
          ],
        },
        firstCode: {
          rules: [
            {
              validateFunction: function (rule, value, data, callback) {
                const reg = /^[0-9]{12}$/;
                const reg1 = /^[0-9]{13}$/;
                const reg2 = /^[0-9]{10}$/;
                console.log('reg', reg.test(value));
                if (!reg.test(value) && !reg1.test(value) && !reg2.test(value)) {
                  callback('请输入12位/13位真实的商品条码或10位自定义条码')
                }
                return true
              }
            },
          ],
        },
        storePrice: {
          rules: [
            {
              required: true,
              errorMessage: '请输入商品售价',
            },
            {
              validateFunction: function (rule, value, data, callback) {
                const reg = /^[0-9]{1,10}(\.[0-9]{1,2})?$/;
                if (!reg.test(value)) {
                  callback('请输入1-10位数字，最多保留2位小数')
                }
                return true
              }
            },
          ],
        },
        purchasePrice: {
          rules: [
            {
              required: true,
              errorMessage: '请输入商品进价',
            },
            {
              validateFunction: function (rule, value, data, callback) {
                const reg = /^[0-9]{1,10}(\.[0-9]{1,2})?$/;
                if (!reg.test(value)) {
                  callback('请输入1-10位数字，最多保留2位小数')
                }
                return true
              }
            },
          ],
        },
      },
    }
  },
  watch: {
    customFormData: {
      handler(newVal, oldVal) {
        if (newVal.name) {
          var reg = /[\u4e00-\u9fa5A-Za-z]/g;
          var names = newVal.name.match(reg);
          let name = ''
          if (names) {
            name = names.join("");
            this.customFormData.mnemonic = pinyin(name, { pattern: "first" })
              .toUpperCase()
              .replace(/\s*/g, "");
          } else {
            this.customFormData.mnemonic = "";
          }
          this.customFormData.name = newVal.name.replace(/(\ud83c[\udc00-\udfff])|(\ud83d[\udc00-\udfff])|(\ud83e[\udc00-\udfff])|[\u2100-\u32ff]|[\u0030-\u007f][\u20d0-\u20ff]|[\u0080-\u00ff]/g, '')
        } else {
          this.customFormData.mnemonic = "";
        }
        if (newVal.storePrice && newVal.purchasePrice) {
          const num = DecimalUtils.divide(DecimalUtils.subtract(newVal.storePrice, newVal.purchasePrice), newVal.storePrice)
          const grossRate = (Math.round(num * 10000) / 100)
          if (isNaN(grossRate)) this.customFormData.grossRate = "0.00";
          else this.customFormData.grossRate = grossRate;
        } else {
          this.customFormData.grossRate = "";
        }
      },
      deep: true,
      immediate: true,
    },
  },
  onLoad(params) {
    this.type = params?.type
    this.id = params?.id
    this.obj = params.obj ? JSON.parse(params.obj) : {}
    if (this.type == '0') {
      this.customFormData.name = this.obj.name
      this.customFormData.mnemonic = this.obj.mnemonic
      this.customFormData.firstCode = this.obj.firstCode
      this.customFormData.storePrice = this.obj.storePrice
      this.customFormData.purchasePrice = this.obj.purchasePrice
      this.customFormData.categoryId = this.obj.categoryId
      this.customFormData.categoryName = this.obj.categoryName
    }
    if (this.type == '1') {
      this.customFormData.categoryName = params?.categoryName
      this.customFormData.categoryId = params?.categoryId
    }
    console.log('params', this.type, this.id, this.obj);
  },
  methods: {
    submitForm() {
      this.$refs.customForm.validate(async (res) => {
        console.log('res', res);
        // return 
        if (!res) {
          console.log('表单数据信息：', this.customFormData);
          let data = {}
          if (this.type == '0') {
            data = {
              ...this.customFormData,
              id: this.id
            }
            const res = await reqUpdateNonstandardCommodity(data)
            if (res.code == 200) {
              uni.showToast({
                title: '修改成功',
                icon: 'none',
                duration: 1000
              })
              setTimeout(() => {
                uni.navigateBack()
              }, 1000)

            }
          } else if (this.type == '1') {
            data = {
              ...this.customFormData
            }
            const res = await reqAddNonstandardCommodity(data)
            if (res.code == 200) {
              uni.showToast({
                title: '添加成功',
                icon: 'none',
                duration: 1000
              })
              setTimeout(() => {
                uni.navigateBack()
              }, 1000)

            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
view {
  box-sizing: border-box;
}

.content {
  height: 100vh;
  background-color: #fff;
}

.main {
  height: calc(100% - 88rpx);
  padding: 20rpx;
  overflow: scroll;
}

.row {
  display: flex;
  // align-items: center;
  height: 80rpx;
  line-height: 80rpx;
  margin-bottom: 60rpx;

  .col {
    width: 90%;
  }

  .col2 {
    width: 70%;
    margin-right: 20rpx;
  }
}

.btnBox {

  width: 100%;
  text-align: center;
}

.btn {
  width: 80%;
  // margin: 0 auto;
  display: inline-block;
  height: 88rpx;
  line-height: 88rpx !important;
  text-align: center;
  color: #fff;
  background-color: #ff6600;
  border-radius: 10rpx;
}
</style>
